<template>
  <div>
    <div class="wrap">
      <div class="title">收货信息</div>

      <div class="infoList" @click="jumpReciveAddrList">
        <div class="left">
          <div class="infoItem">
            <img src="@/assets/name.png" alt="" />
            <em>{{ resAddressInfo.nickName }}</em>
          </div>
          <div class="infoItem">
            <img src="@/assets/tel.png" alt="" />
            <em>{{ resAddressInfo.mobile }}</em>
          </div>
          <div class="infoItem">
            <img src="@/assets/addr2.png" alt="" />
            <em>{{ resAddressInfo.detailsAddress }}</em>
          </div>
        </div>
        <img src="@/assets/rightArrow.png" alt="" class="rightArrow" />
      </div>
      <div class="title">商品信息</div>
      <div class="proContainer">
        <div class="productListWrap">
          <div class="productItem" v-for="(item, index) in resCarGoodsList" :key="index">
            <img :src="$imgUrl + item.listImgUrl" alt="" class="proPosterLeft" />
            <div class="proIntroRight2">
              <p class="proTitle2">{{ item.goodsName }}</p>
              <p class="saleNum2">{{ item.specsName }}</p>
              <div class="priceWrap2">
                <em class="price2">￥{{ item.totalPrice }}</em>
                <van-stepper
                  v-model="item.payNum"
                  theme="round"
                  button-size="18"
                  disable-input
                  @change="onChange(item)"
                />
              </div>
            </div>
          </div>
          <div class="shopDiscounts">
            <em class="shopDisTitle">订单备注</em>
            <div class="inputNotes">
              <van-field
                v-model="notesInput"
                label=""
                placeholder="请输入备注(选填)"
                maxlength="30"
              />
            </div>
          </div>
        </div>
      </div>
      <div class="bgWrap" style="margin-top: 10px">
        <div class="payWayItem" @click="choosePayWay = 0">
          <img src="@/assets/payWay1.png" alt="" class="payWayIcon" />
          <em class="payWayText">余额支付(可用￥{{ resRemainingSum }})</em>
          <img
            src="@/assets/circle.png"
            alt=""
            class="circle"
            v-if="choosePayWay !== 0"
          />
          <img
            src="@/assets/circle2.png"
            alt=""
            class="circle"
            v-if="choosePayWay == 0"
          />
        </div>
        <div class="payWayItem" style="border: 0px solid #111" @click="choosePayWay = 1">
          <img src="@/assets/payWay2.png" alt="" class="payWayIcon" />
          <em class="payWayText">微信支付</em>
          <img
            src="@/assets/circle.png"
            alt=""
            class="circle"
            v-if="choosePayWay !== 1"
          />
          <img
            src="@/assets/circle2.png"
            alt=""
            class="circle"
            v-if="choosePayWay == 1"
          />
        </div>
      </div>
    </div>

    <div>
      <div class="maskWrap" v-if="payMask">
        <div class="maskBg" @click="payMask = false"></div>
        <div class="chooseNumWrap">
          <div class="maskTitle">余额支付密码</div>
          <div class="explain">请输入余额支付密码,以验证身份</div>
          <div class="maskExpalin">
            <van-password-input
              :value="value"
              info="密码为 6 位数字"
              :error-info="errorInfo"
              :focused="showKeyboard"
              @focus="showKeyboard = true"
            />
            <van-number-keyboard
              v-model="value"
              :show="showKeyboard"
              @blur="showKeyboard = false"
            />
          </div>
          <div class="maskBack" @click="payMask = false">返回</div>
        </div>
      </div>
    </div>

    <div class="bottomWrap" v-if="!payMask">
      <div class="total">共{{ this.carCountData.totalCount }}件</div>
      <div class="price">
        合计：<em>￥{{ this.carCountData.totalPrice }}</em>
      </div>
      <div class="sureSubmit" @click="beforPay">确认提交</div>
    </div>
  </div>
</template>

<script>
import { Overlay, Stepper, Field, Checkbox, PasswordInput, NumberKeyboard } from "vant";
import {
  apiUserAddressList,
  apiPlatformGetCartGoodsList,
  apiShopCouponListByShopId,
  apiPlatformUpdateCartGoodsNum,
  apiPlatformCreateGoodsPreOrder,
  apiPlatformGoodsOrderPay,
  apiAppUserInfo,
  apiGetGoodsList,
  apiAddCartGoods,
  apiClearCartGoods,
  apiGetGoodsDetails,
} from "@/request/api"; // api接口
export default {
  name: "App",
  data() {
    return {
      notesInput: "",
      show: false,
      showSend: false,
      checked: false,
      payMask: false,
      GoodsId: this.$route.query.GoodsId, //商品id
      resCarGoodsList: [], //购物车列表数据
      carCountData: {
        totalCount: 0, //总件数
        totalPrice: 0, //总价格
      },
      resAddressInfo: "", //收货地址
      orderNumber: "", //订单号
      resPayInfo: "",
      choosePayWay: -1,
      resRemainingSum: "", //可用余额
      value: "", //支付密码
      errorInfo: "",
      showKeyboard: true,
    };
  },
  watch: {
    value(value) {
      if (this.value.length == 6) {
        console.log("输入完成");
        // this.crateOrder();
        this.getUserEnterOrderPay();
      }
    },
  },
  mounted() {
    console.log("校区信息", JSON.parse(sessionStorage.getItem("chooseSchoolData")));
    this.getCartGoodsList();
    this.getUserAddressList();
    this.getUserInfo();
  },
  methods: {
    //查询用户信息-获取余额
    getUserInfo() {
      apiAppUserInfo({}).then((res) => {
        this.resRemainingSum = res.data.balancePrice;
        console.log("resRemainingSum余额:", this.resRemainingSum);
      });
    },
    //用户收货地址列表：
    getUserAddressList() {
      apiUserAddressList({}).then((res) => {
        res.data.map((item) => {
          if (item.status == 1) {
            //查找默认地址
            this.resAddressInfo = item;
          }
        });
        console.log("收货地址", this.resAddressInfo);
      });
    },

    //请求购物车列表：
    getCartGoodsList() {
      this.carCountData.totalCount = 0;
      this.carCountData.totalPrice = 0;
      apiPlatformGetCartGoodsList({}).then((res) => {
        this.resCarGoodsList = res.data;
        this.resCarGoodsList.map((item) => {
          this.carCountData.totalCount = this.carCountData.totalCount + item.payNum;
          this.carCountData.totalPrice = this.carCountData.totalPrice + item.totalPrice;
           this.carCountData.totalPrice = this.carCountData.totalPrice.toFixed(2)
        });
        console.log("购物车数据", this.resCarGoodsList);
      });
    },
    //修改购物车的数量：
    onChange(data) {
      console.log("修改购物车的数据", data);
      apiPlatformUpdateCartGoodsNum({
        goodsId: this.GoodsId,
        payNum: data.payNum,
        specsId: data.specsId,
      }).then((res) => {
        this.getCartGoodsList();
      });
    },
    //发起支付之前的校验
    beforPay() {
      if (this.choosePayWay == -1) {
        this.$toast.fail("请先选择支付方式");
        return;
      } else if (
        this.choosePayWay == 0 &&
        this.carCountData.totalPrice > this.resRemainingSum
      ) {
        //使用余额支付 余额账户的钱不够支付选择的套餐费用
        this.$toast.fail("余额不足");
        return;
      } 
      else if (this.choosePayWay == 0) {
        this.crateOrder();
        this.payMask = true; //余额支付 打开余额密码输入框、监听输入密码6位自动调起支付函数
      } 
      else if (this.choosePayWay == 1) {
        this.crateOrder(); //微信支付 直接调起支付函数
      }
    },
    //确认提交订单：
    crateOrder() {
      apiPlatformCreateGoodsPreOrder({
        addressId: this.resAddressInfo.id,
        orderRemark: this.notesInput,
      }).then((res) => {
        console.log("创建订单获取订单id", res.data);
        this.orderNumber = res.data.orderNum;
        if(this.choosePayWay == 1){ //微信支付
          this.getUserEnterOrderPay()
        }else{ //余额支付
         
        }
      });
      // // 当前店铺所在校区:
      // var whereShopSchool = JSON.parse(sessionStorage.getItem("chooseSchoolData")) .schoolIName;
      // if (this.resAddressInfo.schoolName == whereShopSchool) {
      //   apiPlatformCreateGoodsPreOrder({
      //     addressId: this.resAddressInfo.id,
      //     orderRemark: this.notesInput,
      //   }).then((res) => {
      //     console.log("创建订单获取订单id", res.data);
      //     this.orderNumber = res.data.orderNum;
      //     this.getUserEnterOrderPay();
      //   });
      // } else {
      //   this.$toast.fail("抱歉！当前商品，仅支持本校区配送。");
      // }
    },
    //根据订单id获取微信支付需要的信息
    getUserEnterOrderPay() {
      apiPlatformGoodsOrderPay({
        orderNum: this.orderNumber,
        payPassword: this.choosePayWay == 0 ? Number(this.value) : "", //余额支付发支付密码，微信支付不需要
        payType: this.choosePayWay,
      }).then((res) => {
        if (res.code == 200 && this.choosePayWay == 0) {
          this.$toast.success("支付成功!");
          //余额支付成功
          this.$router.push({
            path: "/pages/bIndex",
            query: {
              //传递参数
            },
          });
        } else if (res.code == 200 && this.choosePayWay == 1) {
          this.resPayInfo = res.data;
          console.log("微信支付相关信息", this.resPayInfo);
          this.onBridgeReady();
        }
      });
    },
    //调起微信支付：
    onBridgeReady() {
      // alert("sign:", this.resPayInfo.sign);
      var that = this;
      console.log("that.resPayInfo", that.resPayInfo);
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: that.resPayInfo.appId, //公众号ID，由商户传入
          timeStamp: that.resPayInfo.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: that.resPayInfo.nonceStr, //随机串
          package: that.resPayInfo.package,
          signType: that.resPayInfo.signType, //微信签名方式：
          paySign: that.resPayInfo.sign, //微信签名
        },
        function (res) {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            that.$toast.success("支付成功");
            // 使用以上方式判断前端返回,微信团队郑重提示：
            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
            that.$router.push({
              path: "/pages/bIndex",
              query: {},
            });
          }
        }
      );
    },
    //编辑收货地址：
    jumpReciveAddrList() {
      this.$router.push({
        path: "/pages/reciveAddrList",
        query: {
          //传递参数
          formId: 0,
        },
      });
    },
  },
  created() {},
  components: {
    [Overlay.name]: Overlay,
    [Stepper.name]: Stepper,
    [Field.name]: Field,
    [Checkbox.name]: Checkbox,
    [PasswordInput.name]: PasswordInput,
    [NumberKeyboard.name]: NumberKeyboard,
  },
};
</script>

<style scoped>
.wrap {
  background: #f2f4fa;
  padding: 15px;
  /* min-height: calc(100vh - 70px); */
}
.title {
  font-size: 13px;
  font-weight: 400;
  color: #999999;
  margin: 9px 0px;
}
.infoList {
  overflow: hidden;
  width: calc(100% - 30px);
  background: #ffffff;
  border-radius: 20px;
  padding: 15px 15px 5px 15px;
  margin-bottom: 20px;
}
.left {
  float: left;
}
.infoItem {
  height: 20px;
  line-height: 20px;
  display: flex;
  margin-bottom: 15px;
}
.infoItem img {
  width: 17px;
  height: auto;
  align-items: center;
  padding-right: 15.5px;
}
.infoItem em {
  font-size: 14px;
  font-weight: 400;
  color: #000000;
}
.rightArrow {
  float: right;
  width: 5px;
  height: 9px;
  margin-top: 40px;
}
.proContainer {
  background-color: gold;
  width: calc(100% - 30px);
  background: #ffffff;
  border-radius: 20px;
  padding: 15px 15px 5px 15px;
  margin-bottom: 20px;
}
.productListWrap {
}
.productItem {
  overflow: hidden;
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.proPosterLeft {
  width: 24%;
  height: 75px;
}
.proIntroRight2 {
  width: 70%;
}
.proTitle2 {
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-top: 0px;
}
.saleNum2 {
  margin-top: 9px;
  font-size: 10px;
  font-weight: 300;
  color: #666666;
  text-align: left;
  margin-bottom: 0px;
}
.priceWrap2 {
  margin-top: 4px;
  display: flex;
  justify-content: space-between;
}
.price2 {
  font-size: 10px;
  font-weight: bold;
  color: #ff4646;
}
/deep/.van-stepper--round .van-stepper__plus {
  background-color: #f48f5b;
}
/deep/.van-stepper--round .van-stepper__minus {
  border-color: #f48f5b;
  color: #f48f5b;
  background-color: #fff;
}
.shopDiscounts {
  border-top: 1px solid #eeeeee;
  height: 45px;
  line-height: 45px;
}
.shopDisTitle {
  font-size: 13px;
  font-weight: 400;
  color: #000000;
  float: left;
}
.transPrice {
  color: #ff4646;
}
.reduceRules {
  font-size: 13px;
  font-weight: 400;
  color: #f48f5b;
  float: left;
  margin-left: 20px;
}
.rightImg {
  float: right;
  width: 5px;
  height: 9px;
  margin-top: 19px;
}

.inputNotes {
  width: 80%;
  float: left;
}
.van-cell {
  background-color: none;
}
.bottomWrap {
  width: 100%;
  height: 70px;
  line-height: 70px;
  background: #ffffff;
  box-shadow: 0px 3px 12px 0px rgba(0, 0, 0, 0.12);
  border-radius: 20px 20px 0px 0px;
  position: fixed;
  bottom: 0px;
}

.total {
  float: left;
  font-size: 13px;
  color: #000000;
  margin-left: 15px;
  margin-top: 3px;
}

.price {
  float: left;
  font-size: 13px;
  color: #000000;
  margin-left: 30px;
}

.price em {
  color: #ff4646;
  font-size: 20px;
}

.sureSubmit {
  float: right;
  margin-right: 15px;
  width: 95px;
  height: 34px;
  line-height: 34px;
  background: #181818;
  border-radius: 17px;
  font-size: 14px;
  font-weight: 500;
  color: #ffffff;
  margin-top: 15px;
  text-align: center;
}
.maskWrap {
}
.maskBg {
  width: 100%;
  min-height: 100vh;
  opacity: 0.35;
  background-color: #000;
  position: fixed;
  top: 0px;
}
.chooseNumWrap {
  width: calc(90% - 30px);
  background-color: #fff;
  position: fixed;
  top: 15vh;
  border-radius: 20px;
  color: #181818;
  margin-left: 5%;
  padding: 15px;
}
.maskTitle {
  text-align: center;
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 10px;
}
.explain {
  font-size: 12px;
  color: #999;
  text-align: center;
  margin-bottom: 10px;
}
.maskExpalin {
  font-size: 10px;
  font-weight: 300;
  line-height: 20px;
}
.maskBack {
  width: 115px;
  height: 34px;
  line-height: 34px;
  background: #181818;
  border-radius: 17px;
  margin: 0 auto;
  color: #fff;
  text-align: center;
  margin-top: 22px;
}
.discountsTitle {
  font-size: 15px;
  font-weight: 500;
  color: #000000;
  text-align: center;
  margin: 25px 0px;
}
.discountsItem {
  width: 90%;
  margin: 0 auto;
  height: 98px;
  background: #f2f4fa;
  border-radius: 15px;
  margin-bottom: 15px;
}
.topBalck {
  width: 90px;
  height: 20px;
  line-height: 20px;
  background: #181818;
  border-radius: 13px 0px 13px 0px;
  font-size: 12px;
  font-weight: 400;
  color: #ffffff;
  text-align: center;
}

.disCountsMain {
  overflow: hidden;
  margin-top: 20px;
}

.oneLeft {
  color: #ff4646;
  font-size: 20px;
  float: left;
  margin-left: 25px;
  margin-right: 35px;
  margin-top: 10px;
}

.oneLeft em {
  font-size: 12px;
}
.twoLeft {
  float: left;
}
.disPrice {
  font-size: 12px;
  font-weight: 500;
  color: #000000;
}
.date {
  font-size: 10px;
  font-weight: 400;
  color: #666666;
  margin-top: 10px;
}
.threeLeft {
  float: right;
  width: 25px;
  margin-right: 30px;
}
.useDiscount {
  margin-left: 20px;
  font-size: 12px;
  font-weight: 400;
  color: #000000;
}
.sureUseDiscount {
  width: 90%;
  height: 50px;
  line-height: 50px;
  background: #181818;
  box-shadow: 0px 5px 20px 0px rgba(24, 24, 24, 0.26);
  border-radius: 25px;
  font-size: 16px;
  font-weight: 500;
  color: #ffffff;
  text-align: center;
  margin: 30px auto;
}
.chooseNumWrap2 {
  width: 90%;
  left: 5%;
  background-color: #fff;
  position: fixed;
  top: 40vh;
  border-radius: 20px;
}
.sorry {
  font-size: 14px;
  font-weight: 500;
  color: #666666;
  text-align: center;
  margin-top: 35px;
}
.back {
  width: 115px;
  height: 34px;
  line-height: 34px;
  text-align: center;
  background: #181818;
  border-radius: 17px;
  font-size: 14px;
  font-weight: bold;
  color: #ffffff;
  margin: 20px auto;
}
.bgWrap {
  width: calc(95% - 20px);
  padding: 0px 15px;
  margin: 10px auto;
  background: #ffffff;
  border-radius: 20px;
}
.payWayItem {
  height: 50px;
  line-height: 50px;
  border-bottom: 1px solid #eee;
}
.payWayIcon {
  width: 21px;
  height: 19px;
  float: left;
  margin-top: 15px;
}
.payWayText {
  font-size: 14px;
  font-weight: bold;
  padding-left: 10px;
  color: #000000;
  float: left;
}
.circle {
  display: inline-block;
  float: right;
  width: 20px;
  margin-top: 15px;
}
</style>
